package com.ideal.lx_mss.utils;

import com.ideal.lx_mss.common.MssLogs;
import com.ideal.lx_mss.mapper.MssLogsMapper;
import org.apache.logging.log4j.util.PropertiesUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

@Component
public class TextUtils {
    @Autowired
    private MssLogsMapper mssLogsMapper;

    PropertiesUtil properties = new PropertiesUtil("application.properties");
    SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");

    public boolean saveText(List<String> list, String topic, String pullId,String fileUrl,String type){
        String basiPath = properties.getStringProperty("kafka.dataFileUrl");
        // 检查 List 是否为空或为 null
        if (list == null || list.isEmpty()) {
            return false;
        }
        String fileData = sdf.format(new Date());
        String uuid = UUID.randomUUID().toString();

        String fileName = fileUrl;

        File folder = new File(fileName);

        // 判断文件夹是否存在
        if (!folder.exists()) {
            // 不存在则生成文件夹
            boolean result = folder.mkdirs();
            if (result) {
                System.out.println("文件夹生成成功！");
            } else {
                System.out.println("文件夹生成失败！");
            }
        } else {
            System.out.println("文件夹已经存在！");
        }

        String file = fileName+"/"+uuid+".text";



        try (FileWriter fileWriter = new FileWriter(file)) {
            for (String item : list) {
                fileWriter.write(item + "\n");
            }
            System.out.println("Text file generated successfully.");
        } catch (IOException e) {
            //记录
            MssLogs mssLogs = new MssLogs(UUID.randomUUID().toString(), "TextUtils", "saveText", "systemErr", topic, "", "文件写入失败", CommonUtil.getNowDate(), pullId);
            mssLogsMapper.insert(mssLogs);
            e.printStackTrace();
        }
        //记录
        MssLogs mssLogs = new MssLogs(UUID.randomUUID().toString(), "TextUtils", "saveText", type, topic, "", "文件存储，条数："+list.size(), CommonUtil.getNowDate(), pullId);
        mssLogsMapper.insert(mssLogs);

        return true; // 操作成功后返回true
    }


    public boolean saveMultifile(List<String> list, String topic, String pullId){
        String basePath = properties.getStringProperty("kafka.dataFileUrl");
        // 检查 List 是否为空或为 null
        if (list == null || list.isEmpty()) {
            return false;
        }
        String fileDate = sdf.format(new Date());

        String folderName = basePath+"/"+topic+"/"+fileDate+"/"+pullId;

        File folder = new File(folderName);

        // 判断文件夹是否存在，如不存在则生成
        if (!folder.exists() && !folder.mkdirs()) {
            System.out.println("Failed to create a folder!");
            return false;
        }

        // 拆分成多个文件存储
        int threadNum = 10; // 线程数
        int dataSize = list.size(); // 数据量
        int pageSize = (int) Math.ceil((double) dataSize / threadNum); // 每个线程处理的数据量

        ExecutorService executorService = Executors.newFixedThreadPool(threadNum);

        List<Future<Boolean>> futures = new ArrayList<>();

        for (int i = 0; i < threadNum; i++) {
            final int startIndex = i * pageSize;
            final int endIndex = (i == threadNum - 1) ? dataSize : Math.min(startIndex + pageSize, dataSize);

            Callable<Boolean> task = () -> {
                String uuid = UUID.randomUUID().toString();
                String filePath = folderName + "/" + uuid + ".txt";
                try (FileWriter fileWriter = new FileWriter(filePath)) {
                    for (int j = startIndex; j < endIndex; j++) {
                        fileWriter.write(list.get(j) + "\n");
                    }
                    return true;
                } catch (IOException e) {
                    e.printStackTrace();
                    return false;
                }
            };

            futures.add(executorService.submit(task));
        }

        // 关闭线程池
        executorService.shutdown();

        // 等待所有任务完成
        boolean allSuccess = true;
        for (Future<Boolean> future : futures) {
            try {
                allSuccess &= future.get();
            } catch (Exception e) {
                allSuccess = false;
                e.printStackTrace();
            }
        }

        // 如果有任务失败，则删除已创建的文件
        if (!allSuccess) {
            File[] files = folder.listFiles();
            if (files != null) {
                for (File file : files) {
                    if (!file.delete()) {
                        System.out.println("Failed to delete file: " + file.getAbsolutePath());
                    }
                }
            }
        }

        return allSuccess;
    }



}
